
import java.security.GeneralSecurityException;
import java.util.UUID;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author leehoa
 */
//public class Crypto {
//    
//}
public class Crypto {
    
    public static void main(String[] args) throws Exception {
        
        String keyString = "257f4c5874f64c8b8116782a3486cdaf";
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println("key: "+key);
        String input = "100@6006@6006@123@lethanhhai@";
        String src = "Hello world!";
        String en = Crypto.encrypt(input, keyString);
        String de = Crypto.decrypt(en, keyString);  
        System.out.println("encryption: "+en);
        System.out.println("decryption: "+de);
        
    }
	
	    public static String encrypt(String value, String key) throws GeneralSecurityException {
	        SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
	        Cipher cipher = Cipher.getInstance("AES");
	        cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
	        byte[] encrypted = cipher.doFinal(value.getBytes());
	        return byteArrayToHexString(encrypted);
	    }
	
	    public static String decrypt(String message, String key) throws GeneralSecurityException {
	        SecretKeySpec sks = new SecretKeySpec(hexStringToByteArray(key), "AES");
	        Cipher cipher = Cipher.getInstance("AES");
	        cipher.init(Cipher.DECRYPT_MODE, sks);
	        byte[] decrypted = cipher.doFinal(hexStringToByteArray(message));
	        return new String(decrypted);
	    }   
	    
	    private static String byteArrayToHexString(byte[] b){
	        StringBuffer sb = new StringBuffer(b.length * 2);
	        for (int i = 0; i < b.length; i++){
	            int v = b[i] & 0xff;
	            if (v < 16) {
	                sb.append('0');
	            }
	            sb.append(Integer.toHexString(v));
	        }
	        return sb.toString().toUpperCase();
	    }
	   
	    private static byte[] hexStringToByteArray(String s) {
	        byte[] b = new byte[s.length() / 2];
	        for (int i = 0; i < b.length; i++){
	            int index = i * 2;
	            int v = Integer.parseInt(s.substring(index, index + 2), 16);
	            b[i] = (byte)v;
	        }
	        return b;
	    }
	     
	}